package jhc.cn.moviegallery;

import android.net.Uri;
import android.support.annotation.Nullable;
import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by luyanfei on 16-11-23.
 */

public class DoubanFetchr {
    private static final String TAG = DoubanFetchr.class.getName();
    private static final Uri ENDPOINT = Uri.parse("https://api.douban.com/v2/movie/");

    public byte[] getUrlBytes(String urlSpec) throws IOException {
        URL url = new URL(urlSpec);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        try {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            InputStream input = connection.getInputStream();
            if(connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                throw new IOException(connection.getResponseMessage() + ": with " + urlSpec);
            }

            int bytesRead = 0;
            byte[] buffer = new byte[1024];
            while ((bytesRead = input.read(buffer)) > 0) {
                out.write(buffer, 0, bytesRead);
            }
            out.close();
            return out.toByteArray();
        } finally {
            connection.disconnect();
        }
    }

    public String getUrlString(String urlSpec) throws IOException {
        return new String(getUrlBytes(urlSpec));
    }

    public List<GalleryItem> searchMovies(String keyword) {
        Uri searchUri = ENDPOINT.buildUpon()
                .appendPath("search")
                .appendQueryParameter("q", keyword)
                .build();
        return downloadGalleryItems(searchUri.toString());
    }

    public List<GalleryItem> fetchTop250() {
        Uri top250Uri = ENDPOINT.buildUpon()
                .appendPath("top250")
                .appendQueryParameter("start", "0")
                .appendQueryParameter("count", "100")
                .build();
        return downloadGalleryItems(top250Uri.toString());
    }

    public List<GalleryItem> fetchInTheaters() {
        Uri inTheatersUri = ENDPOINT.buildUpon()
                .appendPath("in_theaters")
                .appendQueryParameter("city", "金华")
                .build();
        return downloadGalleryItems(inTheatersUri.toString());
    }

    @Nullable
    private List<GalleryItem> downloadGalleryItems(String url) {
        List<GalleryItem> downloadItems = null;
        try {
            String jsonString = getUrlString(url);
            JSONObject root = new JSONObject(jsonString);
            downloadItems = parseItems(root);
        } catch (IOException e) {
            Log.e(TAG, "Failed to fetch movies", e);
        } catch (JSONException je) {
            Log.e(TAG, "Failed to parse JSON", je);
        }
        return downloadItems;
    }

    private List<GalleryItem> parseItems(JSONObject jsonBody) throws JSONException {
        List<GalleryItem> list = new ArrayList<>();
        JSONArray subjects = jsonBody.getJSONArray("subjects");
        for(int i=0; i<subjects.length(); i++) {
            JSONObject jsonObject = subjects.getJSONObject(i);
            GalleryItem item = new GalleryItem();
            item.setId(jsonObject.getString("id"));
            item.setTitle(jsonObject.getString("title"));
            item.setUrl(jsonObject.getString("alt"));
            item.setImageUrl(jsonObject.getJSONObject("images").getString("medium"));
            list.add(item);
        }
        return list;
    }
}
